package cn.dvptech.remotemate.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.widget.FrameLayout
import android.widget.RelativeLayout
import cn.dvptech.remotemate.screenmirror.server.TcpServer
import cn.dvptech.remotemate.ui.activity.MainActivity
import com.blankj.utilcode.util.GsonUtils

/**
 * 画面手势控制布局
 */
class ControllerLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : RelativeLayout(context, attrs) {

    var tcpServer: TcpServer? = null
    var paths = arrayListOf<Point>()
    var downTime = 0L

    init {
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return super.onInterceptTouchEvent(ev)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        //根据当前画面宽高与被控端画面宽高比计算当前手势位置在被控端的坐标点
        val dimensionRatioX = MainActivity.dimensionRatioX
        val dimensionRatioY = MainActivity.dimensionRatioY
        val targetX = (event.x / dimensionRatioX).toInt()
        val targetY = (event.y / dimensionRatioY).toInt()
        if (event.action == MotionEvent.ACTION_DOWN) {
            //记录按下坐标点
            paths.clear()
            paths.add(Point(targetX, targetY))
            //手势开始时间
            downTime = System.currentTimeMillis()
            return true
        }
        if (event.action == MotionEvent.ACTION_MOVE) {
            //添加移动过程坐标点
            Log.d("123456", "${event.x}/${event.y}, ${targetX}/${targetY}")
            paths.add(Point(targetX, targetY))
            return true;
        }
        if (event.action == MotionEvent.ACTION_UP) {
            //手势抬起发送记录下的手势路径与时长至被控端
            tcpServer?.sendMessage(GsonUtils.toJson(hashMapOf<String, Any>().apply {
                put("type", "CONTROL")
                put("data", hashMapOf<String, Any>().apply {
                    put("paths", paths)
                    put("duration", System.currentTimeMillis() - downTime)
                })
            }))
            return true;
        }

        return super.onTouchEvent(event)
    }
}

class Point(var x: Int, var y: Int)